﻿Imports System.Drawing.Drawing2D

Friend Structure PointRealWorld
    Public x As Double
    Public y As Double
End Structure

Public Class cDeviceSpatialTranslation

    Private mInboundMatrix As Matrix
    Private mOutboundMatrix As Matrix
    Private mScale As Double

    Friend Sub New(ByVal DeviceDimensions As Size, ByVal RealWorldRectangle As cRectangleMetric)

        mInboundMatrix = New Matrix(1, 0, 0, 1, 0, 0)

        With DeviceDimensions
            mInboundMatrix.Scale(.Width, -.Height) 'Scale from 0-1,0-1 raster orientation
        End With
        mInboundMatrix.Translate(0, -1)

        With RealWorldRectangle
            mInboundMatrix.Scale(1 / CSng(.Width), 1 / CSng(.Height))
            mInboundMatrix.Translate(-CSng(.MinimumX), -CSng(.MinimumY))
        End With

        mOutboundMatrix = mInboundMatrix.Clone
        mOutboundMatrix.Invert()

        mScale = CalculateScale()

    End Sub

    Friend ReadOnly Property DeviceTransform() As Matrix
        Get
            Return mInboundMatrix
        End Get
    End Property

    Private Function CalculateScale() As Double

        Dim OutputOne As PointRealWorld
        Dim OutputTwo As PointRealWorld
        Dim Distance As Double

        OutputOne = TranslateDeviceCoordinate(0, 0)
        OutputTwo = TranslateDeviceCoordinate(1, 1)

        Distance = Math.Abs(OutputOne.x - OutputTwo.x)

        Distance = 1 / Distance

        Return Distance

    End Function

    Friend Function TranslateRealWorldDistance(ByVal Length As Double) As Integer

        Length = Length * mScale
        Return CInt(Length)

    End Function

    Friend Function TranslateRealWorldCoordinate(ByRef X As Double, ByRef Y As Double) As Point

        Dim Points As PointF()
        Dim Result As Point

        ReDim Points(0)
        Points(0).X = CSng(X)
        Points(0).Y = CSng(Y)

        mInboundMatrix.TransformPoints(Points)

        Result.X = CInt(Points(0).X)
        Result.Y = CInt(Points(0).Y)

        Return Result

    End Function

    Friend Function TranslateDeviceCoordinate(ByVal X As Integer, ByVal Y As Integer) As PointRealWorld

        Dim Points As PointF()
        Dim Result As PointRealWorld

        ReDim Points(0)
        Points(0).X = CSng(X)
        Points(0).Y = CSng(Y)

        mOutboundMatrix.TransformPoints(Points)

        Result.x = CDbl(Points(0).X)
        Result.y = CDbl(Points(0).Y)

        Return Result

    End Function

End Class
